package com.xiaoxiong.mami.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoxiong.mami.dao.daomain.UserAddress;
import com.xiaoxiong.mami.dao.daomain.UserInfo;
import com.xiaoxiong.mami.http.AppJsonResult;
import com.xiaoxiong.mami.service.UserAddressService;
import com.xiaoxiong.mami.service.UserInfoService;
import io.swagger.annotations.Api;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api("用户地址")
@RequestMapping("/address")
public class UserAddressWeb {

    Logger logger = Logger.getLogger(getClass());

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping(value = "/getAddressByUserId/{userId}", method = RequestMethod.GET)
    public JSONObject getAddressById(@PathVariable("userId") String userId) {

        if (!StringUtils.isEmpty(userId.trim())) {
            List<UserAddress> addressList = userAddressService.getAddressByUserId(userId);
            JSONObject data = new JSONObject();

            if (!CollectionUtils.isEmpty(addressList)) {
                JSONArray addressJson = (JSONArray) JSONArray.toJSON(addressList);
                data.put("addressList", addressJson);
                logger.info("获取用户地址成功: " + data);
                return AppJsonResult.createSuccessResultStr(data);
            }

            return AppJsonResult.createSuccessResultWithMsg(data, "没有更多数据");
        }
        logger.error("获取用户地址失败id :" + userId);
        return AppJsonResult.createErrorResultStr("参数有误");
    }

    @RequestMapping(value = "/getAddressByAddressId/{id}", method = RequestMethod.GET)
    public JSONObject getAddressById(@PathVariable("id") Long id) {
        if (id > 0) {
            UserAddress address = userAddressService.selectByPrimaryKey(id);
            JSONObject data = (JSONObject) JSONObject.toJSON(address);
            if (address != null) {
                logger.info("获取用户地址成功 id :" + data);
                return AppJsonResult.createSuccessResultStr(data);
            }
            return AppJsonResult.createSuccessResultWithMsg(data, "没有更多数据");
        }
        logger.error("获取用户地址失败 id :" + id);
        return AppJsonResult.createErrorResultStr("参数有误");
    }

    @RequestMapping(value = "/deleteAddressByAddressId/{id}", method = RequestMethod.GET)
    public JSONObject deleteAddressByAddressId(@PathVariable("id") Integer id) {
        if (id > 0) {
            Integer result = userAddressService.deleteAddressByAddressId(id);
            if (result == 1) {
                logger.info("删除用户地址成功 参数id: " + id);
                return AppJsonResult.createSuccessResultMsg("删除成功");
            }
        }
        logger.error("删除用户地址失败 参数id: " + id);
        return AppJsonResult.createErrorResultStr("参数有误");
    }


    @RequestMapping(value = "/default/{userId}/{addressId}", method = RequestMethod.POST)
    public JSONObject defaultAddress(@PathVariable String userId,@PathVariable String addressId) {
        userAddressService.updateDefIsNot(userId);
        Integer result = userAddressService.updateAddressDef(userId,addressId,true);
        if (result == 1) {
            return AppJsonResult.createSuccessResultMsg("更新成功");
        }
        return AppJsonResult.createErrorResultStr("");
    }

    @RequestMapping(value = "/getDefault/{userId}", method = RequestMethod.GET)
    public JSONObject getDefault(@PathVariable String userId) {
        List<UserAddress>  userAddresses = userAddressService.getAddressByUserId(userId);

        UserAddress userAddress = null;
        if (userAddresses!=null&&userAddresses.size()>0){
            for (int i = 0; i < userAddresses.size(); i++) {
                if (userAddresses.get(i).getIsDef()){
                    userAddress = userAddresses.get(i);
                    break;
                }
            }
            if (userAddress==null){
                userAddress = userAddresses.get(0);
            }
            JSONObject address = new JSONObject();
            JSONObject data = (JSONObject) JSONObject.toJSON(userAddress);
            address.put("address",data);
            return AppJsonResult.createSuccessResultStr(address);
        }
        return AppJsonResult.createErrorResultStr("");
    }





    @RequestMapping(value = "/updateAddress/{userId}/{addressId}", method = RequestMethod.PUT)
    public JSONObject updateAddressByAddressId(@PathVariable String userId,@PathVariable String addressId, @RequestParam String receiver,
                                               @RequestParam String telephone, @RequestParam String address, @RequestParam String isDef) {
        if (address != null) {
            UserAddress userAddress = new UserAddress();
            userAddress.setUserId(userId);
            userAddress.setReceiver(receiver);
            userAddress.setTelephone(telephone);
            userAddress.setId(Long.valueOf(addressId));
            if ("true".equals(isDef)) {
                userAddress.setIsDef(true);
                userAddressService.updateDefIsNot(userId);
            } else {
                userAddress.setIsDef(false);
            }
            userAddress.setAddress(address);
            Integer result = userAddressService.updateByPrimaryKeySelective(userAddress);
            if (result == 1) {
                logger.info("更新用户地址成功 :" + address);
                return AppJsonResult.createSuccessResultMsg("更新成功");
            }
        }
        logger.error("更新用户地址失败:" + address);
        return AppJsonResult.createErrorResultStr("参数有误");
    }

    @RequestMapping(value = "/addAddress/{userId}", method = RequestMethod.POST)
    public JSONObject addAddress(@PathVariable String userId, @RequestParam String receiver,
                                 @RequestParam String telephone, @RequestParam String address, @RequestParam String isDef) {
        if (userId != null) {
            UserAddress userAddress = new UserAddress();
            userAddress.setUserId(userId);
            userAddress.setReceiver(receiver);
            userAddress.setTelephone(telephone);
            if ("true".equals(isDef)) {
                userAddress.setIsDef(true);
                userAddressService.updateDefIsNot(userId);
            } else {
                userAddress.setIsDef(false);
            }
            userAddress.setAddress(address);
            UserInfo userInfo = userInfoService.selectByUserId(userId);
            if (userInfo == null) {
                return AppJsonResult.createErrorResultStr("该用户不存在");
            }
            Integer result = userAddressService.insertAddress(userAddress);
            if (result == 1) {
                return AppJsonResult.createSuccessResultMsg("添加地址成功");
            }
        }
        logger.error("添加用户地址失败");
        return AppJsonResult.createErrorResultStr("参数有误");
    }

}
